package cn.joybreeze.controller;


import cn.joybreeze.common.result.R;
import cn.joybreeze.common.vo.UserQueryVO;
import cn.joybreeze.common.vo.UserVO;
import cn.joybreeze.model.UserDO;
import cn.joybreeze.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kjwaa
 * @since 2021-09-15
 */
@RestController
@RequestMapping("/user-do")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 获取用户列表，分页
     * @return
     */
    @GetMapping("/list")
    public R getUserList(UserQueryVO queryVO){
        // 为什么这里加了@RequestBody 前端的参数会传不进来
        Page<UserDO> page =new Page<>();
        page.setCurrent(queryVO.getCurrent());
        page.setSize(queryVO.getSize());
        // 条件查询
        //QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        //queryWrapper.like("account", queryVO.getAccount());
        Page<UserDO> doPage = userService.page(page);
        return R.ok(doPage);
    }

    /**
     * 添加用户
     * @param userVO
     * @return
     */
    @PostMapping("/add")
    public R insertUser(@RequestBody UserVO userVO){
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userVO, userDO);
        boolean isSuccess = userService.saveOrUpdate(userDO);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据id更新用户信息
     * @param id
     * @param userVO
     * @return
     */
    @PostMapping("/update/{id}")
    public R updateUser(@PathVariable int id, @RequestBody UserVO userVO){
        // 一定要加@RequestBody，不然不能直接注入到userVO对象中
        UserDO userDO = userService.getById(id);
        BeanUtils.copyProperties(userVO, userDO);
        boolean isSuccess = userService.updateById(userDO);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据id获取单个用户信息
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public R getUserById(@PathVariable int id){
        return R.ok(userService.getById(id));
    }

    /**
     * 根据id删除单条用户记录
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteUser(@PathVariable int id){
        boolean isSuccess = userService.removeById(id);
        if(isSuccess) return R.ok();
        return R.error();
    }




}
